/*
  1.创建两个线程，都对 money 全局变量进行操作
  2.线程1每次对 money 加10
  3.线程2每次对 money 加0.01
  4.如果出现互斥的情况，线程1会输出小数
*/

#include "spu.h"

//是否使用互斥量
#define  mutex_flag   1

float money;
pthread_mutex_t mutex;  //定义互斥量

void *thread_fun1(void *arg)
{
    while(1)
    {
        #if mutex_flag
            pthread_mutex_lock(&mutex); //上锁
        #endif

        money += 10;
        printf("01: money = %.2f\n",money);
        sleep(1);
        
        #if mutex_flag
            pthread_mutex_unlock(&mutex); //解锁
        #endif
    }
    return (void*)1;
}

void *thread_fun2(void *arg)
{
    while(1)
    {
        #if mutex_flag
            pthread_mutex_lock(&mutex); //上锁
        #endif
        money += 0.01;
        // printf("02: money = %.2f\n",money);
        sleep(1);
        #if mutex_flag
            pthread_mutex_unlock(&mutex); //解锁
        #endif
    }
	return (void*)2;
}

int main(int argc, char *argv[])
{	
	int err1, err2;
	pthread_t thread_id1, thread_id2; 
    int s;

    void *__retval;
    
    //首先初始化互斥量，互斥量才可以使用
    pthread_mutex_init(&mutex, NULL);

	err1 = pthread_create(&thread_id1, NULL, thread_fun1, NULL);
	if(err1 != 0)
		printf("create thread01 failed!\n");

    err2 = pthread_create(&thread_id2, NULL, thread_fun2, NULL);
	if(err2 != 0)
		printf("create thread02 failed!\n"); 

    sleep(1);
    pthread_exit(__retval);
}

